package com.mall.order.services;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.order.OrderQueryService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.converter.OrderConverter;
import com.mall.order.dal.entitys.*;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.OrderShippingMapper;
import com.mall.order.dto.*;
import com.mall.order.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 *  ciggar
 * create-date: 2019/7/30-上午10:04
 */
@Slf4j
@Component
@Service
public class OrderQueryServiceImpl implements OrderQueryService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderConverter orderConverter;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;



    /**
     * 查询用户订单信息
     * @param request
     * @return
     */
    @Override
    public OrderListResponse listOrders(OrderListRequest request) {
        OrderListResponse response = new OrderListResponse();
        try {
            request.requestCheck();
            Example example = new Example(Order.class);
            PageHelper.startPage(request.getPage(), request.getSize());
            if (!StringUtils.isEmpty(request.getSort())) {
                example.setOrderByClause(request.getSort());
            } else {
                example.setOrderByClause("update_time desc");
            }
            example.createCriteria()
                    .andEqualTo("userId", request.getUserId())
                    .andNotEqualTo("status", 8);
            // 获取所有订单
            List<Order> orders = orderMapper.selectByExample(example);
            // 如果无订单
            if (orders == null) {
                response.setDetailInfoList(new ArrayList<>());
                response.setTotal(0L);
                return response;
            }
            // 获取订单总数
            PageInfo<Order> pageInfo = new PageInfo<>(orders);
            long total = pageInfo.getTotal();
            // 根据订单id获取详细商品信息
            ArrayList<OrderDetailInfo> detailInfos = new ArrayList<>();
            for (Order order : orders) {
                OrderDetailInfo info = orderConverter.order2detail(order);
                // 获取商品信息
                List<OrderItem> items = orderItemMapper.queryByOrderId(order.getOrderId());
                // 商品图片更改
                for (OrderItem item : items) {
                    String picPath = item.getPicPath();
                    int index = picPath.indexOf(",");
                    if (index != -1) {
                        picPath = picPath.substring(0, index);
                    }
                    item.setPicPath(picPath);
                }
                // 获取物流信息
                OrderShipping shipping = orderShippingMapper.selectByPrimaryKey(order.getOrderId());
                List<OrderItemDto> itemDtos = orderConverter.item2dto(items);
                info.setOrderItemDto(itemDtos);
                OrderShippingDto shippingDto = orderConverter.shipping2dto(shipping);
                info.setOrderShippingDto(shippingDto);
                detailInfos.add(info);
            }
            response.setDetailInfoList(detailInfos);
            response.setTotal(total);
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.info("OrderQueryServiceImpl.orderList occur Exception: " + e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }


    /**
     * 查询订单详情
     * @param request
     * @return
     */
    @Override
    public OrderDetailResponse getOrderDetailById(OrderDetailRequest request) {
        OrderDetailResponse response = new OrderDetailResponse();
        try {
            request.requestCheck();
            String orderId = request.getOrderId();
            // 查询订单基本信息
            Order order = orderMapper.selectByPrimaryKey(orderId);
            response = orderConverter.order2res(order);
            // 商品信息
            List<OrderItem> orderItems = orderItemMapper.queryByOrderId(orderId);
            // 图片信息
            for (OrderItem item : orderItems) {
                String picPath = item.getPicPath();
                int index = picPath.indexOf(",");
                if (index != -1) {
                    picPath = picPath.substring(0, index);
                }
                item.setPicPath(picPath);
            }
            // 物流信息
            OrderShipping shipping = orderShippingMapper.selectByPrimaryKey(orderId);
            // 转换
            List<OrderItemDto> orderItemDtos = orderConverter.item2dto(orderItems);
            OrderShippingDto shippingDto = orderConverter.shipping2dto(shipping);
            response.setOrderItemDto(orderItemDtos);
            response.setOrderShippingDto(shippingDto);
            response.setStatus(order.getStatus());
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());
            return response;
        } catch (Exception e) {
            log.info("OrderQueryServiceImpl.orderList occur Exception: " + e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }
}
